package io.gitee.kotle.android.mvvm.binding

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import io.gitee.kotle.android.utils.getParameterizedType
import java.lang.IllegalArgumentException

interface IMvvmBinding<Binding : ViewBinding> {

    /**
     * Binding变量
     */
    val mBinding: Binding

    /**
     * 通过泛型创建相对应的ViewBinding
     */
    fun onCreateViewBinding(
        self: IMvvmBinding<Binding>,
        inflater: LayoutInflater,
        container: ViewGroup?,
        attach: Boolean = false
    ): Binding {
        return getViewBindingInstance(self, inflater, container, attach)
    }

    /**
     * 这里返回真实创建的ViewBinding
     */
    @Suppress("UNCHECKED_CAST")
    fun getViewBindingClass(self: IMvvmBinding<Binding>): Class<Binding> {
        val javaClass = self.javaClass
        val parameterizedType = javaClass.getParameterizedType()
        val actualTypeArguments = parameterizedType?.actualTypeArguments
        val type =
            actualTypeArguments?.get(0) ?: throw IllegalArgumentException("需要一个ViewBinding类型的泛型")
        return type as Class<Binding>
    }

    /**
     * 这里返回真实创建的ViewBinding对象
     */
    @Suppress("UNCHECKED_CAST")
    fun getViewBindingInstance(
        self: IMvvmBinding<Binding>,
        inflater: LayoutInflater,
        container: ViewGroup?,
        attach: Boolean = false
    ): Binding {
        val bindingCls = self.getViewBindingClass(self)
        return bindingCls.getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        ).invoke(null, inflater, container, attach) as Binding
    }
}